class BikesController < ApplicationController
  before_action only: :index do
    @user = Rails.cache.fetch(request.headers["token"])
    render json: Failure.new("您还未登录") if @user.blank?
  end


  before_action only: :warning do
    if params[:id].blank?
      @bike = Bike.find_by(licenseNum: params[:licenseNumber])
    else
      @bike = Bike.find_by(out_id: params[:id])
    end
    render json: Failure.new("该车辆还未同步到服务器") if @bike.blank?
  end

  before_action only: [:lock, :unlock, :show] do
    @user = Rails.cache.fetch(request.headers["token"])
    render json: Failure.new("您还未登录") if @user.blank?
    @bike = @user.bikes.find_by(id: params[:id])
    render json: Failure.new("您不是该车的车主") if @bike.blank?
  end

  def index
    render json: Success.new(bike: @user.bikes)
  end

  def show
    render json: Success.new(bike: @bike)
  end

  def lock
    begin
      md5_data = {"mobi_num": @user.mobile, "md_five": "itylhogiwuEDjfMK", "set_status": "1", "licenseNumber": @bike.licenseNum}
      req_data = {"mobi_num": @user.mobile, "set_status": "1", "licenseNumber": @bike.licenseNum, "sign": Digest::MD5.hexdigest(md5_data.to_json)}
      req_info = $req_host[@bike.prop.city.to_sym]

      faraday = Faraday.new(url: req_info[:host])
      response = faraday.get req_info[:url], {rtype: 1, data: DesUtil.encrypt(req_data.to_json)}
      result_json = JSON.parse(DesUtil.decrypt(response.body).gsub("=", ":"))
      if result_json["result"]
        if @bike.update(markLat: params[:lat], markLng: params[:lng], lockAddress: result_json["lastaddr"], status: Bike.statuses[:locked])
          render json: Success.new
        else
          render json: Failure.new(@bike.errors.full_messages.join(";"))
        end
      else
        render json: Failure.new("锁车失败")
      end
    rescue Exception => exp
      render json: Failure.new(exp.message)
    end
  end

  def unlock
    begin
      md5_data = {"mobi_num": @user.mobile, "md_five": "itylhogiwuEDjfMK", "set_status": "0", "licenseNumber": @bike.licenseNum}
      req_data = {"mobi_num": @user.mobile, "set_status": "0", "licenseNumber": @bike.licenseNum, "sign": Digest::MD5.hexdigest(md5_data.to_json)}
      req_info = $req_host[@bike.prop.city.to_sym]

      faraday = Faraday.new(url: req_info[:host])
      response = faraday.get req_info[:url], {rtype: 1, data: DesUtil.encrypt(req_data.to_json)}
      result_json = JSON.parse(DesUtil.decrypt(response.body).gsub("=", ":"))
      if result_json["result"]
        if @bike.unlocked!
          render json: Success.new
        else
          render json: Failure.new(@bike.errors.full_messages.join(";"))
        end
      else
        render json: Failure.new("锁车失败")
      end
    rescue Exception => exp
      render json: Failure.new(exp.message)
    end
  end

  def warning
    if @bike.warning!
      SmsJob.perform_now(@bike.user.mobile, $template[:warning], ["车牌号为#{@bike.licenseNum}的车辆"])
      PushJob.perform_now(
          @bike.user.device_type,
          @bike.user.device_token,
          "车牌号为#{@bike.licenseNum}的车辆存在异常,请及时查看，以免造成损失",
          {bike_id: @bike.id}
      )
      render json: Success.new
    else
      render json: Failure.new(@bike.errors.full_messages.join(";"))
    end
  end
end
